package com.cs.pk.form;

import java.util.Iterator;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.pk.preferences.build.BuildForm;
import org.pk.preferences.build.RemoteBuildForm;

import com.cs.pk.Activator;
import com.cs.pk.clearcase.interfaces.ControlInterface;
import com.cs.pk.form.dialog.InformationControl;
import com.cs.pk.form.dialog.StatusControl;
import com.cs.pk.form.dialog.TitleControl;

//TODO : remove CustomListItems and sync with BuildTreeItems
public class BuildConfigurationForm implements SelectionListener {

    private TreeItem local, remote, selected = null;
    private String message[] = { "Add item ", "Remove item", "Update item" };
    private Image img[] = null;
    ToolItem removeBuilItem = null;
    private Control parent = null;

    public Control createContents(Composite parent) {
	this.parent = parent;
	img = new Image[] {
		Activator.getImageDescriptor("icons/web.gif").createImage(),
		Activator.getImageDescriptor("icons/web.gif").createImage(),
		Activator.getImageDescriptor("icons/web.gif").createImage() };
	TitleControl titleControl = new TitleControl("Build Configuration....");
	titleControl.createControl(parent);
	createBodyControl(parent);
	StatusControl statusControl = new StatusControl("Bottom");
	statusControl.createControl(parent);
	Button actions[] = statusControl.createButtons(new String[] { "Build",
		"Save", "Close" }, 3);
	for (int i = 0; i < actions.length; i++) {
	    actions[i].addSelectionListener(this);
	}
	return parent;
    }

    private void createBodyControl(Composite parent) {

	GridData gridData = new GridData(GridData.FILL_BOTH);
	gridData.grabExcessHorizontalSpace = true;
	gridData.grabExcessVerticalSpace = true;
	SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);
	sashForm.setLayoutData(gridData);
	sashForm.setLayout(new GridLayout());
	createTreeControl(sashForm);
	createConfiguration(sashForm);
	sashForm.setWeights(new int[] { 20, 80 });

    }

    private void createTreeControl(Composite parent) {
	Composite config = new Composite(parent, SWT.BORDER | SWT.NONE);
	GridData gridData = new GridData(GridData.FILL_BOTH);
	gridData.grabExcessVerticalSpace = true;
	gridData.verticalIndent = 0;
	gridData.horizontalIndent = 0;
	config.setLayoutData(gridData);
	config.setLayout(new GridLayout());
	createToolBar(config);
	Tree buildTree = new Tree(config, SWT.SINGLE | SWT.H_SCROLL
		| SWT.V_SCROLL | SWT.BORDER);
	buildTree.addSelectionListener(this);
	GridData data = new GridData(GridData.FILL_BOTH);
	data.grabExcessVerticalSpace = true;
	buildTree.setLayoutData(data);
	local = new TreeItem(buildTree, SWT.NONE);
	local.setText("Local Build");

	local.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(
		ISharedImages.IMG_OBJ_ELEMENT));
	remote = new TreeItem(buildTree, SWT.NONE);
	remote.setText("Remote Build");

	remote.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(
		ISharedImages.IMG_OBJ_ELEMENT));
        
	Iterator itr = Activator.getDefault().localBuildItems.iterator();
	String buildN = null;
	while (itr.hasNext()) {
	    buildN = itr.next().toString();
	    TreeItem treeItem = new TreeItem(local, SWT.NONE);
	    treeItem.setText(buildN);
	    treeItem.setData(buildN);
	}
	local.setExpanded(true);
	itr = Activator.getDefault().remoteBuildItems.iterator();
	while (itr.hasNext()) {
	    buildN = itr.next().toString();
	    TreeItem treeItem = new TreeItem(remote, SWT.NONE);
	    treeItem.setText(buildN);
	    treeItem.setData(buildN);
	}

	buildTree.select(local);
	remote.setExpanded(true);

    }

    public void selectDefault() {
	Event e = new Event();
	e.data = local.getParent();
	e.doit = true;
	local.getParent().notifyListeners(SWT.Selection, e);
    }

    private void createToolBar(Composite parent) {
	ToolBar toolBar = new ToolBar(parent, SWT.WRAP | SWT.RIGHT);
	GridData gd = new GridData(GridData.FILL_HORIZONTAL);
	gd.grabExcessHorizontalSpace = true;
	gd.verticalIndent = 0;
	gd.horizontalIndent = 0;
	toolBar.setLayoutData(gd);
	toolBar.setLayout(new GridLayout());
	ToolItem addBuilItem = new ToolItem(toolBar, SWT.PUSH);
	// Image icon = new Image(parent.getDisplay(), "icons/web.gif");
	// addBuilItem.setImage(icon);
	addBuilItem.setImage(PlatformUI.getWorkbench().getSharedImages()
		.getImage(ISharedImages.IMG_OBJ_ADD));
	addBuilItem.addSelectionListener(new SelectionListener() {

	    public void widgetDefaultSelected(SelectionEvent e) {
	    }

	    public void widgetSelected(SelectionEvent e) {
		addItemToBuildTree(selected);

	    }

	});
	removeBuilItem = new ToolItem(toolBar, SWT.PUSH);
	// icon = new Image(parent.getDisplay(), "icons/web.gif");
	// removeBuilItem.setImage(icon);
	removeBuilItem.setImage(PlatformUI.getWorkbench().getSharedImages()
		.getImage(ISharedImages.IMG_TOOL_DELETE));
	removeBuilItem.addSelectionListener(new SelectionListener() {

	    public void widgetDefaultSelected(SelectionEvent e) {

	    }

	    public void widgetSelected(SelectionEvent e) {
		removeItemFromBuildTree(selected);
	    }

	});
	removeBuilItem.setEnabled(false);
    }

    private final String localItemName = "NewLocalBuildItem_";
    private final String remoteItemName = "NewRemoteBuildItem_";

    private void addItemToBuildTree(TreeItem item) {

	TreeItem newItem = null;
	if (item.getParentItem() == null) {
	    if (checkForUpdate()) {
		TreeItem items[] = item.getItems();
		int counter = 1;
		String itemName = null;
		if (item == local) {
		    itemName = localItemName;
		} else {
		    itemName = remoteItemName;
		}
		for (int i = 0; i < items.length; i++) {
		    TreeItem item_ = items[i];
		    String data = (String) item_.getData();
		    if (data.startsWith(itemName)) {
			String intVal = data.substring(itemName.length());
			try {
			    int count = Integer.parseInt(intVal);
			    if (counter <= count) {
				counter = count + 1;
			    }
			} catch (NumberFormatException nfe) {

			}
		    }
		}

		newItem = new TreeItem(item, SWT.NONE);
		newItem.setText(itemName + counter);
		newItem.setData(itemName + counter);
		newItem.getParent().select(newItem);

		Event e = new Event();
		e.data = newItem.getParent();
		e.doit = true;
		newItem.getParent().notifyListeners(SWT.Selection, e);
		if (item == local) {
		    Activator.getDefault().appendToLocalBuiltItem(
			    itemName + counter);
		} else {
		    Activator.getDefault().appendToRemoteBuiltItem(
			    itemName + counter);
		}
		Activator.getDefault().saveBuildItems();
	    }
	} else {
	    addItemToBuildTree(item.getParentItem());
	}

    }

    private void removeItemFromBuildTree(TreeItem item) {
	MessageBox mb = new MessageBox(parent.getShell(), SWT.ICON_WARNING
		| SWT.YES | SWT.NO);
	mb.setMessage("Do you want to delete build item " + selected.getText()
		+ " ?\n ");
	int retval = mb.open();
	if (retval == SWT.YES) {

	    TreeItem parent = item.getParentItem();
	    TreeItem items[] = parent.getItems();
	    TreeItem newSelection = null;
	    for (int i = 0; i < items.length; i++) {
		TreeItem item_ = items[i];
		if (item_ == item) {
		    BuildForm bf = (BuildForm) item.getData("BUILD_FORM");
		    bf.removeOld();
		    if (parent == local) {
			Activator.getDefault().removeLocalBuildItem(
				item_.getData().toString());
		    } else {
			Activator.getDefault().removeRemoteBuildItem(
				item_.getData().toString());
		    }
		    item.dispose();
		    item = null;
		    newSelection = i > 0 ? items[i - 1] : parent;
		    newSelection.getParent().select(newSelection);
		    Event e = new Event();
		    e.data = newSelection.getParent();
		    e.doit = true;
		    newSelection.getParent().notifyListeners(SWT.Selection, e);
		    Activator.getDefault().saveBuildItems();
		    break;
		}
	    }
	}

    }

    private Composite buildConfig = null;;

    private void createConfiguration(Composite parent) {

	buildConfig = new Composite(parent, SWT.BORDER);
	GridData gridData = new GridData(GridData.FILL_BOTH);
	buildConfig.setLayoutData(gridData);
	buildConfig.setLayout(new GridLayout());

    }

    public static void main(String args[]) {
	Display display = new Display();
	Shell shell = new Shell(display);
	GridData data = new GridData(GridData.FILL_BOTH);
	shell.setLayoutData(data);
	shell.setLayout(new GridLayout());
	BuildConfigurationForm bcf = new BuildConfigurationForm();
	bcf.createContents(shell);

	shell.open();
	display.update();
	while (!shell.isDisposed()) {
	    if (!display.readAndDispatch())
		display.sleep();
	}
	display.dispose();
    }

    public void widgetDefaultSelected(SelectionEvent e) {

    }

    private boolean checkForUpdate() {
	return checkForUpdate(true);
    }

    private boolean checkForUpdate(boolean showDialog) {
	if (selected != null && !selected.isDisposed()
		&& selected.getData() != null) {
	    ControlInterface bf = (ControlInterface) selected.getData("BUILD_FORM");
	    if (!bf.save()) {
		if (showDialog) {
		    MessageBox mb = new MessageBox(parent.getShell(),
			    SWT.ICON_INFORMATION | SWT.YES | SWT.NO
				    | SWT.CANCEL | SWT.LEFT_TO_RIGHT);
		    mb.setMessage("Changes for build item "
			    + selected.getText()
			    + " is not saved.\n Do you want to save it?");
		    int retval = mb.open();
		    if (retval == SWT.YES) {

			updateRepository(bf);

		    } else if (retval == SWT.NO) {
			bf.discardChanges();
		    } else {
			selected.getParent().select(selected);
			return false;
		    }
		} else {
		    updateRepository(bf);
		}
	    }
	}
	return true;
    }

    private void updateRepository(ControlInterface bf) {
	if (selected.getParentItem() == local) {
	    Activator.getDefault().removeLocalBuildItem(
		    selected.getData().toString());
	} else {
	    Activator.getDefault().removeRemoteBuildItem(
		    selected.getData().toString());
	}

	bf.saveChanges();

	if (selected.getParentItem() == local) {
	    Activator.getDefault().appendToLocalBuiltItem(
		    selected.getData().toString());
	} else {
	    Activator.getDefault().appendToRemoteBuiltItem(
		    selected.getData().toString());
	}
		Activator.getDefault().saveBuildItems();
    }
    
    ControlInterface bf = null; 

    public void widgetSelected(SelectionEvent e) {
	if (e.getSource() instanceof Tree) {
	    TreeItem item = ((Tree) e.getSource()).getSelection()[0];
	    if (selected != item) {
		if (!checkForUpdate()) {
		    return;
		}
		Control control[] = buildConfig.getChildren();
		for (int i = 0; i < control.length; i++) {
		    control[i].dispose();
		}
		Composite build = new Composite(buildConfig, SWT.NONE);
		GridData gridData = new GridData(GridData.FILL_BOTH);
		build.setLayoutData(gridData);
		build.setLayout(new GridLayout());
		bf = null;
		if (item.getData() == null) {
		    bf = InformationControl.getNewInstance(message, img);
		    // informationControl.createInfoControl(build);
		    removeBuilItem.setEnabled(false);
		} else {

		    if (item.getParentItem()== local) {
			bf = BuildForm.getNewInstance();
		    } else {
			bf = RemoteBuildForm.getNewInstance();
		    }
		    removeBuilItem.setEnabled(true);
		    item.setData("BUILD_FORM", bf);
		}
		bf.openForm(build, item);
		bf.fillValues();
		buildConfig.layout(true);
		selected = item;
	    }
	} else if (e.getSource() instanceof Button) {
	    Button act = (Button) e.getSource();
	    if (act.getText().equals("Build")) {
		// TODO
	    } else if (act.getText().equals("Save")) {
		checkForUpdate(false);
	    } else if (act.getText().equals("Close")) {
		checkForUpdate();
		parent.dispose();
	    }

	}
    }

    public void dispose() {
	if (img != null) {
	    for (int i = 0; i < img.length; i++) {
		if (img[i] != null) {
		    img[i].dispose();
		    img[i] = null;
		}
	    }
	}

    }
    
    public void repaint(){
	if(bf!=null ){
	    bf.repaint();
	}
    }

}
